package com.trt.user.controller;

import com.trt.api.BaseController;
import com.trt.api.controller.user.UserControllerApi;
import com.trt.enums.ResponseStatusEnum;
import com.trt.pojo.AppUser;
import com.trt.pojo.dto.AppUserBO;
import com.trt.pojo.vo.AppUserBasicInfoVO;
import com.trt.pojo.vo.AppUserVO;
import com.trt.user.service.IUserService;
import com.trt.utils.ApiResult;
import com.trt.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.Map;

/**
 * @author tanrentao
 * @date 2021-12-02
 * @desc
 */
@RestController
public class UserController extends BaseController implements UserControllerApi {

    @Autowired
    private IUserService userService;

    @Override
    public ApiResult getAppUserInfo(String userId) {
        // 1.判断参数不能为空
        if (StringUtils.isBlank(userId)) {
            return ApiResult.errorCustom(ResponseStatusEnum.UN_LOGIN);
        }

        // 2.根据userId查询用户的信息
        AppUser appUser = getUser(userId);

        // 3. 返回用户信息
        AppUserVO appUserVO = new AppUserVO();
        BeanUtils.copyProperties(appUser, appUserVO);

        return ApiResult.success(appUserVO);
    }

    @Override
    public ApiResult getAppUserBasicInfo(String userId) {
        // 1.判断参数不能为空
        if (StringUtils.isBlank(userId)) {
            return ApiResult.errorCustom(ResponseStatusEnum.UN_LOGIN);
        }

        // 2.根据userId查询用户的信息
        AppUser appUser = getUser(userId);

        // 3. 返回用户信息
        AppUserBasicInfoVO appUserBasicInfoVO = new AppUserBasicInfoVO();
        BeanUtils.copyProperties(appUser, appUserBasicInfoVO);

        return ApiResult.success(appUserBasicInfoVO);
    }

    private AppUser getUser(String userId) {
        // 查询判断redis中是否包含用户信息，如果包含，则获取redis中信息后直接返回，就不去查询数据库了
        String appUserJson = redisUtils.get(REDIS_USER_INFO + ":" + userId);
        AppUser appUser = null;
        if (StringUtils.isNotBlank(appUserJson)) {
            appUser = JsonUtils.jsonToPojo(appUserJson, AppUser.class);
        } else {
            appUser = userService.selectUser(userId);
            // 由于用户信息不怎么会变动，对于一些千万级别的网站来说，这类信息不会直接去查询数据库
            // 那么完全可以依靠redis，直接把查询后的数据存入到redis中
            redisUtils.set(REDIS_USER_INFO + ":" + userId, JsonUtils.objectToJson(appUser));
        }
        return appUser;
    }

    @Override
    public ApiResult updateAppUser(@Valid AppUserBO appUserBO, BindingResult result) {
        // 1.校验BO
        if (result.hasErrors()) {
            Map<String, String> map = getErrors(result);
            return ApiResult.errorMap(map);
        }

        // 2.更新用户信息
        userService.updateAppUser(appUserBO);

        return ApiResult.success();
    }
}
